﻿#pragma once

#include <functional>
#include <mutex>
#include <string>
#include <unordered_map>
#include <vector>

#include "json11.hpp"

namespace asycipc {

class ConfigService {
 public:
  bool LoadFromFile(const std::string& path, std::string* error = nullptr);
  bool ReloadIfChanged(std::string* error = nullptr);

  json11::Json Get(const std::string& path) const;
  int GetInt(const std::string& path, int default_value) const;
  double GetDouble(const std::string& path, double default_value) const;
  bool GetBool(const std::string& path, bool default_value) const;
  std::string GetString(const std::string& path,
                        const std::string& default_value) const;

  void RegisterListener(const std::string& key, std::function<void()> callback);

 private:
  std::string config_path_;
  std::string last_raw_;
  json11::Json root_;
  mutable std::mutex mutex_;
  std::unordered_multimap<std::string, std::function<void()>> listeners_;

  void Notify(const std::string& key) const;
  json11::Json ResolvePath(const std::string& path) const;
};

}  // namespace asycipc

